package com.happyhome.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.happyhome.constants.ComUnitName;
import com.happyhome.constants.RecordStatus;
import com.happyhome.datamodel.HouseUtility;
import com.happyhome.datamodel.QHouse;
import com.happyhome.datamodel.QHouseUtility;
import com.happyhome.datamodel.QUtility;
import com.mysema.query.BooleanBuilder;
import com.mysema.query.jpa.JPQLQuery;
import com.mysema.query.jpa.impl.JPAQuery;
import com.trg.dao.jpa.GenericDAOImpl;

@Repository
public class HouseUtilityDaoImpl extends GenericDAOImpl<HouseUtility, Long> implements HouseUtilityDao{
	
	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory.getLogger(HouseUtilityDaoImpl.class);
	
	@Override
	@PersistenceContext(unitName = ComUnitName.COM_UNIT)
	public void setEntityManager(EntityManager entityManager) {
		super.setEntityManager(entityManager);
	}

	@Override
	public List<Object[]> getAllUtilityByHouseId(Long houseId) {
		JPQLQuery query = new JPAQuery(em());
		
		QHouse house = QHouse.house;
		QUtility utility = QUtility.utility;
		QHouseUtility houseUtility = QHouseUtility.houseUtility;
		
		BooleanBuilder where = new BooleanBuilder();
		
		where.and(house.status.eq(RecordStatus.TRUE))
			 .and(utility.status.eq(RecordStatus.TRUE))
			 .and(house.idHouse.eq(houseId));
		
		query.from(houseUtility)
			.leftJoin(houseUtility.house, house)
			.leftJoin(houseUtility.utility, utility)
			.where(where);
		
		List<Object[]> result = query.list(house.idHouse, utility.idUtility, utility.codeUtility, utility.nameUtility);
		return result;
	}

	@Override
	public List<HouseUtility> getAllUtilitiesOfHouse(Long houseId) {
			JPQLQuery query = new JPAQuery(em());
			
		QHouse house = QHouse.house;
		QHouseUtility houseUtility = QHouseUtility.houseUtility;
		
		BooleanBuilder where = new BooleanBuilder();
		
		where.and(house.status.eq(RecordStatus.TRUE))
			 .and(houseUtility.status.eq(RecordStatus.TRUE))
			 .and(house.idHouse.eq(houseId));
		
		query.from(houseUtility)
			.leftJoin(houseUtility.house, house)
			.where(where);
		
		List<HouseUtility> result = query.list(houseUtility);
		return result;
	}
	
}
